﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TugasAkhir.Models;
using TugasAkhir.Objects;

namespace TugasAkhir
{
    public partial class DaftarRekomendasiGAGAL : System.Web.UI.Page
    {
        private DataSet hasilQuery;
        private DosenObject dosen;

        protected void Page_Load(object sender, EventArgs e)
        {
            CheckSession();
            CheckRole();
            if (!Page.IsCallback)
            {
                this.InitDropdownPertanyaan();

                if (Request.QueryString["key"] != null && Request.QueryString["key"] != "")
                {
                    if (!PertanyaanModel.CekId(Request.QueryString["key"]))
                    {
                        string url = Request.Url.AbsolutePath.Split(new char[] {'?'})[0];
                        Response.Redirect(url, true);
                    }
                    this.ddlPertanyaanSm.SelectedValue = Request.QueryString["key"];

                    this.InitTabelRekomendasi(Request.QueryString["key"]);
                }
            }
        }

        private void CheckRole()
        {
            if (int.Parse(Session["id_role"].ToString().Substring(2)) == 2)
            {
                this.liPertanyaan.Attributes.Remove("hidden");
                this.liPengaturanPertanyaan.Attributes.Remove("hidden");
                this.liAnalisis.Attributes.Remove("hidden");
                this.liRekomendasi.Attributes.Remove("hidden");
            }
            else if (int.Parse(Session["id_role"].ToString().Substring(2)) == 3)
            {
                this.liAnalisis.Attributes.Remove("hidden");
                this.liRekomendasi.Attributes.Remove("hidden");
            }
            else
            {
                this.liRekomendasi.Attributes.Remove("hidden");
                this.liAnalisis.Attributes.Remove("hidden");
                this.liPengaturanRekomendasi.Attributes.Remove("hidden");
                this.liDaftarRekomendasi.Attributes.Remove("hidden");
            }
        }

        private void CheckSession()
        {
            if (Session["id_role"] != null && int.Parse(Session["id_role"].ToString().Substring(2)) >= 4)
            {
                DosenModel.GetDosenDetail(Session["username"].ToString(), out this.dosen);
                this.litName.Text = dosen.NamaDosen;
            }
            else
            {
                Response.Redirect("/Login.aspx");
            }
        }

        private void InitTabelRekomendasi(string key)
        {
            bool flag = RekomendasiModel.GetRekomendasi(key, out hasilQuery);
            if (flag)
            {
                this.gvRekomendasi.DataSource = this.hasilQuery.Tables[0];
                this.gvRekomendasi.DataBind();
            }
        }

        private void InitDropdownPertanyaan()
        {
            var tanggal = new TanggalObject();
            TanggalModel.GetServerWaktu(out tanggal);

            string periodeSekarang = (tanggal.Bulan >= 1 && tanggal.Bulan <= 6) ? "GENAP" : "GASAL";
            string tahunSekarang = (periodeSekarang == "GENAP") ? (String.Format("{0}-{1}", tanggal.Tahun - 1, tanggal.Tahun)) : (String.Format("{0}-{1}", tanggal.Tahun, tanggal.Tahun + 1));

            var data = new DataSet();
            bool flag = AnalisisModel.GetPertanyaan(tahunSekarang, out data);

            if (flag)
            {
                foreach (DataRow item in data.Tables[0].Rows)
                {
                    this.ddlPertanyaanSm.Items.Add(new ListItem(item[1].ToString(), item[0].ToString()));
                }
            }
        }

        protected void btAddRekomendasi_Click(object sender, EventArgs e)
        {
            string idRekomendasi;
            RekomendasiModel.GetId(out idRekomendasi);

            string idPertanyaan = this.ddlPertanyaanSm.SelectedValue;

            var rekomendasi = new RekomendasiObject();
            rekomendasi.IdRekomendasi = idRekomendasi;
            rekomendasi.IdPertanyaan = idPertanyaan;
            rekomendasi.Rekomendasi = this.tbAddRekomendasi.Text;

            bool flag = RekomendasiModel.TambahRekomendasi(rekomendasi);
            if (flag)
            {
                this.InitTabelRekomendasi(Request.QueryString["key"]);
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "HideAddScript", "HideAdd();", true);
            }
        }

        protected void btDeleteRekomendasi_Click(object sender, EventArgs e)
        {
            bool flag = RekomendasiModel.HapusRekomendasi(this.hfDeleteID.Value);

            if (flag)
            {
                this.InitTabelRekomendasi(Request.QueryString["key"]);
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "HideAddScript", "HideDelete();", true);
            }
        }

        protected void gvRekomendasi_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName.Equals("updateRecord"))
            {
                int index = Convert.ToInt32(e.CommandArgument);
                this.EditCommand(index);
            }
            else if (e.CommandName.Equals("deleteRecord"))
            {
                int index = Convert.ToInt32(e.CommandArgument);
                this.DeleteCommand(index);
            }
        }

        protected void SetHiddenField(int index, ref HiddenField hiddenField)
        {
            string code = gvRekomendasi.DataKeys[index].Value.ToString();
            hiddenField.Value = code;
        }

        private void EditCommand(int index)
        {
            this.SetHiddenField(index, ref this.hfUpdateID);
            var rekomendasi = new RekomendasiObject();

            RekomendasiModel.GetDetailRekomendasi(this.hfUpdateID.Value, out rekomendasi);
            this.txtEditRekomendasi.Text = rekomendasi.Rekomendasi;

            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "ShowEditScript", "ShowEdit();", true); 
        }

        private void DeleteCommand(int index)
        {
            this.SetHiddenField(index, ref this.hfDeleteID);

            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "ShowDeleteScript", "ShowDelete();", true); 
        }

        protected void gvRekomendasi_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            this.gvRekomendasi.PageIndex = e.NewPageIndex;
            this.InitTabelRekomendasi(Request.QueryString["key"]);

            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "InitScript", "Init();", true);
        }

        protected void btEditRekomendasi_Click(object sender, EventArgs e)
        {
            var editedRekomendasi = new RekomendasiObject();
            editedRekomendasi.IdRekomendasi = this.hfUpdateID.Value;
            editedRekomendasi.IdPertanyaan = this.ddlPertanyaanSm.SelectedValue;
            editedRekomendasi.Rekomendasi = this.txtEditRekomendasi.Text;

            bool flag = RekomendasiModel.UbahRekomendasi(editedRekomendasi);

            if (flag)
            {
                this.InitTabelRekomendasi(Request.QueryString["key"]);
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "HideEditScript", "HideEdit();", true);
            }
        }

        protected void lnkLogout_Click(object sender, EventArgs e)
        {
            Session["id_role"] = "";
            Session["username"] = "";
            CheckSession();
        }
    }
}